# -*- coding: UTF-8 -*-
import urllib.parse
import urllib.request


import pymysql
from django.http import JsonResponse
from django.shortcuts import get_object_or_404 ,render

from public.function import Public
from saltstack.salt_api import SaltAPI
from .models import Game,Game_Update_log,Mysql
import time
from userlog.function import SaveUserlog
from cmdb.models import Server
from myauth.models import PlatForm

import threading

class Public_GAME_OPERATION(object):
    def __init__(self,*args,**kwargs):
        super(Public_GAME_OPERATION, self).__init__()
        self.Saltapi = SaltAPI()
        self.optiondict={}

    def post(self):
        sid = self.request.POST.get("serverid", '')
        self.game = get_object_or_404(Game, pk=int(sid))
        self.minionid = self.game.server.ip
        func = self.request.GET.get('option','undefined')

        try:
            return getattr(self, func)() #类反射机制 自动调用html传来的对应的参数名称
        except Exception as e:
            print (e)
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % str(e)})


    def saltfunction_nojson(self,minionid,func,args):
        saltreturn = self.Saltapi.remote_execution(minionid, fun=func, arg=args)
        return saltreturn


    def saltfunction(self,minionid,func,args):
        saltreturn = self.Saltapi.remote_execution(minionid, fun=func, arg=args)
        # print(saltreturn)
        return JsonResponse({"msg": '''<p style="color:green;font-size:15px ">%s</p>''' % str(saltreturn)})

    def cat_game_status(self):
        func = "cmd.run"
        args = "cd /data/game/%s/server/ && ./game_ctl status >/dev/null 2>&1 && sh  /data/game/%s/server/check_running.sh %s" % (self.game.game_user,self.game.game_user,self.game.game_user)
        return self.saltfunction(self.minionid, func, args)


    def cat_game_conf(self):
        func="cmd.run"
        args="cat /data/game/%s/server/config/deploy.py" %(self.game.game_user)
        return self.saltfunction(self.minionid,func,args)

    def cat_game_ver(self):
        func="cmd.run"
        args="svn info  /data/game/%s/server" %(self.game.game_user)
        return self.saltfunction(self.minionid, func, args)


    def mv_log(self):
        print("mv_log")
        func="cmd.run"
        args="cd /data/game/%s/server &&  /bin/bash mv_log.sh  " %(self.game.game_user)
        self.saltfunction_nojson(self.minionid,func,args)
        update_dic = {"name": self.game.name, "update_action": "mv_log",
                      "game_user": self.game.game_user, "oprate_user": self.request.user,
                      "server_ip": str(self.game.server)}
        Game_Update_log.objects.create(**update_dic)

    def start_game(self):
        func = "cmd.run"
        args = "cd /data/game/%s/server/ && ./game_ctl  start   >/dev/null 2>&1  && sleep 5 && echo  " % (self.game.game_user)
        #args="echo $PATH"
        print('start_game')
        self.saltfunction_nojson(self.minionid,func,args)
        update_dic = {"name": self.game.name, "update_action": "start_game",
                      "game_user": self.game.game_user, "oprate_user": self.request.user,
                      "server_ip": str(self.game.server)}
        Game_Update_log.objects.create(**update_dic)
        print('abcdef')
        return self.cat_game_status()



    def restart_game(self):
        self.stop_game()
        self.start_game()
        return self.cat_game_status()


    def stop_game(self):
        func = "cmd.run"
        args = "cd /data/game/%s/server/ && ./game_ctl  stop  && sleep 15 && ./game_ctl  stop && ./game_ctl  shutdown   " % (self.game.game_user)

        self.saltfunction(self.minionid, func, args)
        update_dic = {"name": self.game.name, "update_action": "stop_game",
                      "game_user": self.game.game_user, "oprate_user": self.request.user,
                      "server_ip": str(self.game.server)}
        Game_Update_log.objects.create(**update_dic)
        thread1 = threading.Thread(target=self.mv_log)
        thread1.start() #转移日志
        return self.cat_game_status()






    def url_get(self,request,*args,**kwargs):
        self.request = request
        cls = SaveUserlog()
        cls(request)
        if self.request.method == "POST":
            return self.post()
        else:
            return  JsonResponse({"msg":'''<p style="color:red;font-size:12px ">不支持的http request method"}</p>'''})

    def update_game(self):
        func = "cmd.run"
        now_time=time.strftime('%Y-%m-%d_%H:%M',time.localtime(time.time()))
        args = "export LC_ALL='en_US.UTF-8';cd /data/game/%s/server/  && \
         mkdir -pv  svnlog && svn up  --username=luojiaojun --password=Wdsfa238F --force >svnlog/%s.txt 2>&1 && echo $? " % (self.game.game_user,now_time)
        svn_returns=self.saltfunction_nojson(self.minionid, func, args)
        #保存更新日志到本地
        args1="cat /data/game/%s/server/svnlog/%s.txt"  %(self.game.game_user,now_time)
        self.svnuplog=self.saltfunction_nojson(self.minionid, func, args1)
        print(self.game.name,self.game.server)
        update_dic={"name":self.game.name,"update_action":"svn up",
                    "update_result":svn_returns,'update_more_info':self.svnuplog,
                    "game_user":self.game.game_user,"oprate_user":self.request.user,
                    "server_ip":str(self.game.server)}
        Game_Update_log.objects.create(**update_dic)
        if svn_returns != '0':
            msg="svn update 失败!!请检查更新日志"
            return JsonResponse({"msg":'''<p style="color:red;font-size:12px ">%s</p>''' %msg})
        else:
            msg="svn up更新成功"
            html='''<p style="color:green;font-size:12px ">%s&nbsp;&nbsp;&nbsp;&nbsp;\
            <input class="btn btn-warning" type="button" id="edit" value="查看更新记录" onclick="alert('%s')" /></p>''' % (msg,self.svnuplog)
            return JsonResponse({"msg": html})


    def update_opentime(self):
        func = "cmd.run"
        config_file = '/data/game/%s/server/config/deploy.py' % (self.game.game_user)

        args=r'''export LC_ALL='en_US.UTF-8';sed -i '/open_time/ c\t\t\t\t\t"open_time": "%s",' %s  && dos2unix   %s''' %(self.game.open_date,config_file,config_file)
        self.saltfunction_nojson(self.minionid, func, args)

        args2='''awk -F'"'  '/open_time/ {print $4}'   %s   ''' %(config_file)
        saltreturns=self.saltfunction_nojson(self.minionid, func, args2)
        print(saltreturns,self.game.open_date)
        if str(saltreturns) != str(self.game.open_date):
            msg = "修改开服时间失败!!"
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % msg})
        self.restart_game()
        args = "cd /data/game/%s/server/ &&  ./game_ctl status >/dev/null 2>&1 &&  /bin/bash   /data/game/%s/server/check_running.sh %s" % (
            self.game.game_user, self.game.game_user, self.game.game_user)
        result = self.Saltapi.remote_execution(self.minionid, fun=func, arg=args)
        print(result)
        if result == "OK - servers is running":
            msg = "修改开服时间成功!!"
            return JsonResponse({"msg": '''<p style="color:green;font-size:12px ">%s</p>''' % msg})
        else:
            msg = "修改开服时间失败!!"
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % msg})



    def cat_game_open_time(self):
        func = "cmd.run"
        config_file = '/data/game/%s/server/config/deploy.py' % (self.game.game_user)
        args = '''awk -F'"'  '/open_time/ {print $4}'   %s   ''' % (config_file)
        saltreturns = self.saltfunction_nojson(self.minionid, func, args)
        return JsonResponse({"msg": '''<p style="color:green;font-size:12px ">%s</p>''' % saltreturns})


    def hot_update_example1(self):
        func='cmd.run'
        self.update_game()
        args="export LC_ALL='en_US.UTF-8'; cd /data/game/%s/server/ &&  ./game_ctl st >/dev/null    && ./game_ctl  reload && sleep 5 "  %self.game.game_user
        saltreturns = self.saltfunction_nojson(self.minionid, func, args)
        args2='''export LC_ALL='en_US.UTF-8'; cd /data/game/%s/server/ &&  grep "reload role gameMgrs system"  .scene_nohup.out |tail -n 2'''  %(self.game.game_user)
        saltreturns2=self.saltfunction_nojson(self.minionid, func, args2)
        msg='reload_result: '+saltreturns+'\nlog_result: '+saltreturns2
        return JsonResponse({"msg": '''<p style="color:green;font-size:12px ">%s</p>''' % msg})











    def update_and_restart_game(self):
        try:
            self.stop_game()
            self.update_game()

            self.start_game()
            func="cmd.run"
            args = "cd /data/game/%s/server/ &&  ./game_ctl status >/dev/null 2>&1 &&  /bin/bash   /data/game/%s/server/check_running.sh %s" % (
            self.game.game_user, self.game.game_user, self.game.game_user)
            result = self.Saltapi.remote_execution(self.minionid, fun=func, arg=args)
            print(result)
            if result=="OK - servers is running":
                msg="更新并重启成功"
                html = '''<p style="color:green;font-size:12px ">%s &nbsp;&nbsp;&nbsp;&nbsp; \
                <input class="btn btn-warning" type="button" id="edit" value="查看更新记录" onclick="alert('%s')" /></p>''' % (msg, self.svnuplog)
                return JsonResponse({"msg": html })
            else:
                return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">重启失败%s</p>''' %result})
        except Exception as e:
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % str(e)})



    def get_game_ports(self,sceenid):
        api_url="http://14.29.122.34:5000/api/getport/?sceenid=%s" %sceenid
        headers = {'User-Agent': "curl-7.19.7"}
        req = urllib.request.Request(api_url,headers=headers)
        response = urllib.request.urlopen(req)
        data = response.read().decode('utf-8')
        print(data)
        dic={}
        for line in data:
            line=line.split(":")
            key=line[0]
            value=line[1]
            dic[key]=value

        return dic


    def one_key_install_game(self):

        sceenid=self.game.game_id
        if self.game.state != -1:
            return JsonResponse({"msg":"游戏状态非未安装"},safe=False)
        portdict=self.get_game_ports(sceenid)
        print(portdict)
        #修改游戏安装状态为正在安装
        self.game.state=1
        self.game.save()
        #更改或者添加mysql /mongo db数据库连接
        return JsonResponse({"msg":"安装成功"},safe=False)



    def one_key_truancate(self):
        func = "cmd.run"
        now_time = time.strftime('%Y-%m-%d_%H', time.localtime(time.time()))
        args = "export LC_ALL='en_US.UTF-8';salt-call state.sls shell  >/dev/null  &&  \
        cd /data/shell/game/ && /bin/bash game_truncate_db.sh  %s  " %(self.game.game_user)
        self.saltfunction_nojson(self.minionid, func, args)
        ck_status_args="cat /data/log/game_truncate/%s/%s_log.txt"  %(self.game.game_user,now_time)
        ck_result=self.saltfunction_nojson(self.minionid, func, ck_status_args)

        if ck_result == "游戏清档并且启动成功":

            return JsonResponse({"msg": '''<p style="color:green;font-size:12px ">%s</p>''' % ck_result})
        else:
            return JsonResponse({"msg": '''<p style="color:red;font-size:12px ">%s</p>''' % ck_result})







class Game_Public(Public):
    def get_mysql_con(self):
        configdict={"host":"122.226.199.218","db":"gm","user":"readonly","passwd":"readonly", "charset":"utf8",'cursorclass':pymysql.cursors.DictCursor}
        try:
            conn=pymysql.connect(**configdict)
            return conn
        except Exception as e:
            print(e)
            raise  ValueError(e)

    def update_game_db_pwd(self):
        conn=self.get_mysql_con()
        cursor=conn.cursor()
        sid = self.request.POST.get("serverid", '')
        self.game = get_object_or_404(Game, pk=int(sid))
        query_string="select  game_db_user,game_db_pwd,gm_db_user,gm_db_pwd,log_db_user,log_db_pwd from server_list where game_id=%s" %(self.game.game_id)
        cursor.execute(query_string)
        data=cursor.fetchone()
        print(data)
        cursor.close()
        conn.close()
        return  JsonResponse({"msg":"ok"})


    def sync_game_list(self):
        conn = self.get_mysql_con()
        cursor = conn.cursor()
        query_string = '''select  server_name,login_ip1,test_flag,game_id,game_db_ip,log_db_user,open_time from server_list where log_db_user like  "tq_%" '''
        cursor.execute(query_string)
        result=cursor.fetchall()
        game_type_dict={"0":"s","1":"t"}
        print('更新之前清除所有的数据')
        Game.objects.all().delete()
        for gamedic in result:
            name=gamedic['server_name']
            version='1.5'
            state='0'
            game_user=gamedic['log_db_user']
            server_id=Server.objects.get(ip=gamedic['login_ip1'])
            phone_type='android'
            # open_date=gamedic['open_time']
            # if int(open_date) ==0:
            open_date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            test_flag=str(gamedic['test_flag'])
            game_type=game_type_dict[test_flag]
            game_id=gamedic['game_id']
            platform = PlatForm.objects.get(name='37wan')
            mysql=Mysql.objects.get(server=server_id,mysql_type='master')
            # print(name,version,state,game_user,server_id,phone_type,open_date,game_id,mysql)
            update_dic = {"name": name, 'version':version,
                          "game_user": game_user, 'state':state,'server':server_id,'phone_type':phone_type,
                          'game_type':game_type,'mysql':mysql,'game_id':game_id,'platform':platform,
                          'open_date':open_date}
            try:
                Game.objects.create(**update_dic)
            except Exception as e:
                print(e)

        return JsonResponse({"msg": "同步成功"})




class Test_Game_Public(Game_Public):
    def get(self,*args,**kwargs):  #分页相关
        form = self.form
        search_form = self.searchform(auto_id=False)
        ONE_PAGE_OF_DTAA = 0
        try:
            curpage = int(self.request.GET.get('curpage', '1'))
            allpage = int(self.request.GET.get('allpage', '1'))
            try:
                ONE_PAGE_OF_DTAA = int(self.request.COOKIES["pageper"])
            except Exception:
                pass
        except ValueError as  e:
            print(e)
            curpage = 1
            allpage = 1
            pagetype = ''
            ONE_PAGE_OF_DTAA = 15

        if ONE_PAGE_OF_DTAA == 0:
            ONE_PAGE_OF_DTAA = 10
        startops = (curpage - 1) * ONE_PAGE_OF_DTAA
        endpos = startops + ONE_PAGE_OF_DTAA
        posts = self.models.objects.filter(game_type__in=['t','d'])[startops:endpos]

        # print startops, endpos
        if curpage == 1 and allpage == 1:
            allpostcounts = len(self.models.objects.filter(game_type__in=['t','d']))
            allpage = allpostcounts // ONE_PAGE_OF_DTAA
            remainpost = allpostcounts % ONE_PAGE_OF_DTAA
            if remainpost > 0:
                allpage += 1
        pagelist = range(1, int(allpage) + 1)
        url_name =self.url_name
        return render(self.request, self.template_name, locals())

